package com.dongdong.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.dongdong.mapper.TbAddressMapper;
import com.dongdong.model.TbAddress;
import com.dongdong.model.TbAddressExample;
import com.dongdong.service.AddressService;
import com.dongdong.utils.JwtUtil;
import com.dongdong.vo.AddressVO;
import com.dongdong.vo.UserLoginVO;
import com.dongdong.vo.UserVO;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private TbAddressMapper addressMapper;

    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public List<AddressVO> getAddressByUserId(String accessToken) {
        Claims claims = jwtUtil.parseJwt(accessToken);
        String subject = claims.getSubject();
        UserLoginVO vo = JSONObject.parseObject(subject, UserLoginVO.class);

        TbAddressExample example = new TbAddressExample();
        example.createCriteria().andUserIdEqualTo(vo.getUsername());

        List<TbAddress> tbAddresses = addressMapper.selectByExample(example);
        List<AddressVO> voList = tbAddresses.stream().map((x) -> {
            AddressVO addressVO = new AddressVO();
            BeanUtils.copyProperties(x, addressVO);
            return addressVO;
        }).collect(Collectors.toList());
        return voList;
    }

    @Override
    public TbAddress getAddressById(Long addrId) {
        return addressMapper.selectByPrimaryKey(addrId);
    }

    @Override
    public void addAddress(String accessToken, AddressVO addressVO) {
        Claims claims = jwtUtil.parseJwt(accessToken);
        String subject = claims.getSubject();
        UserVO userVO = JSONObject.parseObject(subject, UserVO.class);
        TbAddress address = new TbAddress();
        BeanUtils.copyProperties(addressVO,address);
        address.setUserId(userVO.getUsername());
        address.setIsDefault("1");
        address.setCreateDate(new Date());
        addressMapper.insertSelective(address);
    }
}
